package com.fingard.dsp.bank.directbank.cfcc01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.util.DateHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.util.Calendar;
import java.util.Date;

/**
 * @author Parker on 2019-08-08.
 * @version 1.0
 */
public class CFCC01Transaction extends CFCC01Base implements ITransaction {
    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        //历史明细查询返回ATS的对象
        RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
        retAts.writeStart();//写返回ATS的统一头部信息
        String tmpRespCode = "";
        String tmpRespInfo = "";
        try {
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7516.getDateFrom());

            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7516.getDateTo());

            int tmpIntDateFrom = 0;
            int tmpIntDateTo = 0;
            //按自然月循环查询
            while (tmpIntDateFrom <= tmpIntDateTo && tmpRespCode.length() == 0) {
                Calendar tmpClndrStepTo = Calendar.getInstance();
                tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
                //判断是否跨月
                if (DateHelper.compareMonth(tmpCalendarFrom, tmpCalendarTo) == -1) {
                    //跨月则设置为月末
                    tmpClndrStepTo.set(Calendar.DAY_OF_MONTH, tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
                } else {
                    tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
                }
                XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                CFCC01Header bankHeader = new CFCC01Header();
                //今日明细
                if (p_req7516.dateFrom.equals(p_req7516.dateTo) && p_req7516.dateFrom.equals(Format.Date8Format.format(new Date()))) {
                    bankHeader.transCode = "todayTranDetailQuery";
                } else {
                    bankHeader.transCode = "historyTranDetailQuery";
                }
                writeCommonHeader(xmlWriter, bankHeader);
                xmlWriter.writeStartElement("REQUEST");
                xmlWriter.writeElementString("TRANTYPE", "004");
                xmlWriter.writeElementString("UNIQUECODE", getQryTransID());//唯一码
                xmlWriter.writeElementString("CUSTID", bankFront.org);//唯一码
                xmlWriter.writeElementString("ACCTNO", p_req7516.actNum);
                xmlWriter.writeElementString("CURRENCY", convertCurToBank(p_req7516.actCur));
                if (!(p_req7516.dateFrom.equals(p_req7516.dateTo) && p_req7516.dateFrom.equals(Format.Date8Format.format(new Date())))) {
                    xmlWriter.writeElementString("BEGINDATE", Format.Date10Format.format(tmpCalendarFrom.getTime()));//查询起始日期
                    xmlWriter.writeElementString("ENDDATE", Format.Date10Format.format(tmpClndrStepTo.getTime()));//查询结束日期
                }
                xmlWriter.writeElementString("ACCTFLAG", "0");//账号标志 0：财务公司结算账号1：银行账号
                xmlWriter.writeEndDocument();
                String[] tmpRetBkStr = sendToBank(xmlWriter.toXmlString());
                if (tmpRetBkStr[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpRetBkStr[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        String returnCode = tmpBkReader.getFirstText("/TRANSACTION/HEADER/REP_CODE");
                        String returnMsg = tmpBkReader.getFirstText("/TRANSACTION/HEADER/REP_DESC");

                        if (returnCode != null && returnCode.equals("0000")) {
                            while (tmpBkReader.read("/TRANSACTION/RESPONSE/LIST")) {
                                RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
                                XElement tmpRecord = tmpBkReader.readedXElement;
                                tmpRetDetail.actNum = p_req7516.actNum;
                                tmpRetDetail.actArea = p_req7516.actArea;
                                tmpRetDetail.cur = p_req7516.actCur;
                                tmpRetDetail.recAccNum = tmpRecord.getSingleText("OPPACCTNO");
                                tmpRetDetail.recAccName = tmpRecord.getSingleText("OPPACCTNAME");
                                tmpRetDetail.cdFlag = tmpRecord.getSingleText("CDFLAG").equalsIgnoreCase("借") ? "1" : "2";//借贷标志 D支出
                                tmpRetDetail.tranAmt = Format.DecimalAmtFormat.format(Double.parseDouble(tmpRecord.getSingleText("TRANAMT").replace(",", "")));
                                tmpRetDetail.tranDate = tmpRecord.getSingleText("TRANDATE");
                                tmpRetDetail.valueDate = tmpRetDetail.tranDate;
                                tmpRetDetail.tranTime = tmpRetDetail.tranDate + " 00:00:00";
                                tmpRetDetail.postTimestamp = tmpRetDetail.tranTime;
                                tmpRetDetail.accBal = Format.DecimalAmtFormat.format(Double.parseDouble(tmpRecord.getSingleText("BALANCE").replace(",", "")));
                                tmpRetDetail.usage = tmpRecord.getSingleText("SUMMARY");//摘要
                                //对账码
                                tmpRetDetail.abstr = pickupAbstr(tmpRecord.getSingleText("SUMMARY"), tmpRecord.getSingleText("MEMO"));//待确定
                                tmpRetDetail.comment = tmpRecord.getSingleText("MEMO");//备注
                                retAts.writeRetDetail(tmpRetDetail);
                            }
                        } else {
                            tmpRespCode = "-1";
                            tmpRespInfo = returnMsg;
                            retAts = new RetAtsTrans(p_req7516.reqHeader);
                            retAts.writeStart();
                            retAts.writeRespCode(tmpRespCode);
                            retAts.writeRespInfo(tmpRespInfo);
                            WriteBankLogLn(tmpRespCode + ":"+tmpRespInfo);
                            retAts.writeEnd();
                            return retAts;
                        }
                    } else {
                        tmpRespCode = "-1";
                        tmpRespInfo = tmpSbMsg.toString();
                        retAts = new RetAtsTrans(p_req7516.reqHeader);
                        retAts.writeStart();
                        retAts.writeRespCode(tmpRespCode);
                        retAts.writeRespInfo(tmpRespInfo);
                        WriteBankLogLn(tmpRespCode + ":"+tmpRespInfo);
                        retAts.writeEnd();
                        return retAts;
                    }
                } else {
                    tmpRespCode = "-1";
                    tmpRespInfo = tmpRetBkStr[1];
                    retAts = new RetAtsTrans(p_req7516.reqHeader);
                    retAts.writeStart();
                    retAts.writeRespCode(tmpRespCode);
                    retAts.writeRespInfo(tmpRespInfo);
                    WriteBankLogLn(tmpRespCode + ":"+tmpRespInfo);
                    retAts.writeEnd();
                    return retAts;
                }

                tmpCalendarFrom = tmpClndrStepTo;
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            }
        } catch (Exception e) {
            tmpRespCode = "-1";
            tmpRespInfo =  "查询失败：" + e.getMessage();
            e.printStackTrace();
            retAts = new RetAtsTrans(p_req7516.reqHeader);
            retAts.writeRespCode(tmpRespCode);
            retAts.writeRespInfo(tmpRespInfo);
            WriteBankLogLn(tmpRespCode + ":"+tmpRespInfo);
            retAts.writeEnd();
            return retAts;
        }

        if ("-1".equals(tmpRespCode)) {
            retAts.writeRespCode(tmpRespCode);
            retAts.writeRespInfo(tmpRespInfo);
        } else if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("交易为空!");
        }
        retAts.writeEnd();
        return retAts;
    }

    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        //通用历史余额查询
        Req7516HisTrans tmpReq7516 = new Req7516HisTrans(p_req7515.reqHeader);
        tmpReq7516.actArea = p_req7515.actArea;
        tmpReq7516.actCur = p_req7515.actCur;
        tmpReq7516.actNum = p_req7515.actNum;
        String tmpStrToday = Format.Date8Format.format(new Date());
        tmpReq7516.dateFrom = tmpStrToday;
        tmpReq7516.dateTo = tmpStrToday;
        return d_7516_HisTrans(tmpReq7516);
    }
}
